package com.zmj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zmj.dto.SysMenuDTO;
import com.zmj.dto.TableData;
import com.zmj.entity.SysMenu;
import com.zmj.mapper.SysMenuMapper;
import com.zmj.utils.Response;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysMenuService {
    @Resource
    private SysMenuMapper sysMenuMapper;

    public TableData findMenu(String search,String order,int limit,int offset){
        PageHelper .offsetPage(offset,limit);
        List<SysMenuDTO> list =sysMenuMapper.findMenu(search,order);
        PageInfo pageInfo=new PageInfo(list);

        long total=pageInfo.getTotal();
        List<SysMenu> menuList =pageInfo.getList();
        TableData tableData=new TableData();
        tableData.setRows(menuList);
        tableData.setTotal(total);
        return  tableData;
    }

    public List<SysMenu> findTreeMenu(){
        List<SysMenu> list=sysMenuMapper.findTreeMenu();
        SysMenu sysMenu=new SysMenu();
        sysMenu.setMenuId((long)0);
        sysMenu.setParentId((long)-1);
        sysMenu.setName("一级目录");
        sysMenu.setType(0);
        list.add(sysMenu);
        return list;
    }

    public Response save(SysMenu sysMenu){
        int i=sysMenuMapper.insertSelective(sysMenu);
        return i>0?Response.success():Response.error("新增失败");
    }

    public Response findMenuById(long menuId){
        SysMenu sysMenu=sysMenuMapper.selectByPrimaryKey(menuId);
        return Response.success().put("menu",sysMenu);
    }

    public  Response update(SysMenu sysMenu){
        int i=sysMenuMapper.updateByPrimaryKeySelective(sysMenu);
        return  i>0?Response.success():Response.error("修改失败");
    }
    public Response del(List<Long> ids){
        for(Long id:ids) {
            if (id <= 28) {
                return Response.error("系统内置菜单不能删除");
            }
        }
            int i=sysMenuMapper.del(ids);
            return  i>0?Response.success():Response.error("删除失败");
        }

    public Response findUserMenu(long userId){
        List<SysMenuDTO> dir=sysMenuMapper.findDirByUserId(userId);
        for (SysMenuDTO menuDTO:dir) {
                List<SysMenuDTO> list=sysMenuMapper.findMenuByUserIdAndParentId(userId,menuDTO.getMenuId());
                menuDTO.setList(list);
        }
        return Response.success().put("menuList",dir).put("permissions","[]");
    }
 }
